package com.sunnyweather.android.ui.weather

import android.content.Context
import android.graphics.Color
import android.icu.text.SimpleDateFormat
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowInsets
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.sunnyweather.android.R
import com.sunnyweather.android.databinding.ActivityWeatherBinding
import com.sunnyweather.android.databinding.ForecastItemBinding
import com.sunnyweather.android.logic.model.Weather
import com.sunnyweather.android.logic.model.getSky
import java.util.Locale

class WeatherActivity : AppCompatActivity() {

    val viewModel by lazy {
        ViewModelProvider(this).get(WeatherViewModel::class.java)
    }

    private lateinit var awBinding: ActivityWeatherBinding

    fun getAwBinding() = awBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        awBinding = ActivityWeatherBinding.inflate(layoutInflater)
        setContentView(awBinding.root)

        // 设置状态栏为透明
        window.statusBarColor = Color.TRANSPARENT

        // 设置导航栏为透明（如果需要的话）
        window.navigationBarColor = Color.TRANSPARENT

        // 设置为全屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.setDecorFitsSystemWindows(false)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val ab = window.attributes
            ab.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            window.attributes = ab
        }

        //隐藏状态栏
        val controller = WindowCompat.getInsetsController(window, awBinding.root)
        controller.hide(WindowInsetsCompat.Type.systemBars())
        controller.systemBarsBehavior =
            WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE

        if (viewModel.locationLng.isEmpty()) {
            viewModel.locationLng = intent.getStringExtra("location_lng") ?: ""
        }
        if (viewModel.locationLat.isEmpty()) {
            viewModel.locationLat = intent.getStringExtra("location_lat") ?: ""
        }
        if (viewModel.placeName.isEmpty()) {
            viewModel.placeName = intent.getStringExtra("place_name") ?: ""
        }
        viewModel.weatherLiveData.observe(this) { result ->
            val weather = result.getOrNull()
            if (weather != null) {
                showWeatherInfo(weather)
            } else {
                Toast.makeText(this, "无法成功获取天气信息", Toast.LENGTH_SHORT).show()
                result.exceptionOrNull()?.printStackTrace()
            }
            awBinding.swipeRefresh.isRefreshing = false
        }
        awBinding.swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
        refreshWeather()
        awBinding.swipeRefresh.setOnRefreshListener {
            refreshWeather()
        }

        awBinding.nowLayout.navBtn.setOnClickListener {
            awBinding.drawLayout.openDrawer(GravityCompat.START)
        }
        awBinding.drawLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerClosed(drawerView: View) {
                val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(
                    drawerView.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            }

            override fun onDrawerOpened(drawerView: View) {}

            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}

            override fun onDrawerStateChanged(newState: Int) {}
        })
    }

    fun refreshWeather() {
        viewModel.refreshWeather(viewModel.locationLng, viewModel.locationLat)
        awBinding.swipeRefresh.isRefreshing = true
    }

    private fun showWeatherInfo(weather: Weather) {
        awBinding.apply {
            nowLayout.placeName.text = viewModel.placeName
            val realtime = weather.realtime
            val daily = weather.daily
            // 填充now.xml布局中的数据
            val currentTempText = "${realtime.temperature.toInt()} °C"
            nowLayout.currentTemp.text = currentTempText
            nowLayout.currentSky.text = getSky(realtime.skycon).info
            val currentPM25Text = "空气指数 ${realtime.airQuality.aqi.chn.toInt()}"
            nowLayout.currentAQI.text = currentPM25Text
            nowLayout.nowLayout.setBackgroundResource(getSky(realtime.skycon).bg)
            // 填充forecast.xml布局中的数据
            forecastLayout.forecastLayout.removeAllViews()
            val days = daily.skycon.size
            for (i in 0 until days) {
                val skycon = daily.skycon[i]
                val temperature = daily.temperature[i]
                val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                val fiBinding = ForecastItemBinding.inflate(layoutInflater)
                fiBinding.dateInfo.text = simpleDateFormat.format(skycon.date)
                val sky = getSky(skycon.value)
                fiBinding.skyIcon.setImageResource(sky.icon)
                fiBinding.skyInfo.text = sky.info
                val tempText = "${temperature.min.toInt()} ~ ${temperature.max.toInt()} °C"
                fiBinding.temperatureInfo.text = tempText
                forecastLayout.forecastLayout.addView(fiBinding.root)
            }
            // 填充life_index.xml布局中的数据
            val lifeIndex = daily.lifeIndex
            lifeIndexLayout.coldRiskText.text = lifeIndex.coldRisk[0].desc
            lifeIndexLayout.dressingText.text = lifeIndex.dressing[0].desc
            lifeIndexLayout.ultravioleText.text = lifeIndex.ultraviolet[0].desc
            lifeIndexLayout.carWashingText.text = lifeIndex.carWashing[0].desc
            weatherLayout.visibility = View.VISIBLE
        }
    }
}